<!DOCTYPE HTML>
<html lang="zh" xml:th="http://www.thymeleaf.org">
<head>
    <title>物联网设备调试</title>
    <link rel="stylesheet" th:href="@{/statics/bootstrap/4.6.0/bootstrap.min.css}" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/bootstrap/4.6.0/bootstrap.min.js}"></script>
    <script th:src="@{/statics/system/common.js}"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>

<body>
    <div class="container">
        <div class="form-group">
            <h3 th:text="${pageName}">物联网设备调试</h3>
            <div class="alert alert-info" role="alert" style="margin-bottom: 0">
                <div class="text-muted"><span th:text="|连接到 ${serverInfo}|"></span></div>
            </div>
            <input type="hidden" name="token" id="token" th:value="${token}">
        </div>

        <div class="card-body" style="display: flex;flex-wrap: wrap; padding: 0">
            <div class="form-group">
                <div class="input-group input-group-sm">
                    <div class="input-group-prepend">
                        <div class="input-group-text">发送订阅</div>
                    </div>
                    <input id="sendTopic" type="text" class="form-control" th:value="${sendTopic}" />
                </div>
            </div>

            <div class="form-group">
                <div class="input-group input-group-sm">
                    <div class="input-group-prepend">
                        <div class="input-group-text">接收订阅</div>
                    </div>
                    <input id="receiveTopic" type="text" class="form-control" th:value="${receiveTopic}" />
                </div>
            </div>

            <div class="form-group" hidden="hidden">
                <div class="input-group input-group-sm">
                    <div class="input-group-prepend">
                        <div class="input-group-text">QoS</div>
                    </div>
                    <input id="qos" min="0" max="2" type="number" class="form-control" th:value="${qos}" />
                </div>
            </div>

            <div class="form-group">
                <button onclick="reConnect()" class="btn btn-primary btn-sm">修改订阅</button>
                <button onclick="closeWebSocket()" class="btn btn-danger btn-sm">关闭连接</button>
            </div>
        </div>

        <div class="form-group">
            <div class="input-group input-group-sm">
                <div class="input-group-prepend">
                    <div class="input-group-text">自定义调试信息</div>
                </div>
                <input id="text" type="text" class="form-control" placeholder="请输入调试信息">
                <div class="input-group-append">
                    <button onclick="send()" class="btn btn-primary btn-sm" type="button">发送</button>
                </div>
            </div>
        </div>
        <div class="form-group" th:hidden="${batchSend == 0}">
            <div class="card">
                <div class="card-header">

                    <div style="display: flex;flex-wrap: wrap;align-items: center;">
                        <button id="showHide" onclick="showHide()" class="btn btn-link">
                            ▷
                        </button>
                        <span style="margin-left: 20px">批量下发参数</span>
                        <span style="margin-left: 50px" class="text-muted">间隔：</span>
                        <input th:value="${batchDelay}" type="number" id="batchInterval" value="1000" style="width: 80px" class="form-control form-control-sm">
                        <span> ms</span>
                        <button style="margin-left: 20px" onclick="batchSend()" class="btn btn-primary btn-sm">批量发送</button>

                    </div>
                </div>
                <div id="batchCommand" class="card-body" style="padding: 6px 6px;">
                    <span style="display: block" id="hideText"></span>
                    <textarea th:text="${batchCommand}" id="batchText" class="form-control" style="height: 120px;display: none;margin-bottom: 20px;font-size: 13px"></textarea>
                </div>
            </div>
        </div>
        <div class="form-group" th:if="${params.size() > 0}">
            <div class="card">
                <div class="card-header">
                    预设调试参数
                </div>
                <div class="card-body" style="padding: 6px 6px;">
                    <table class="table">
                        <tbody>
                        <tr th:each="p : ${params}">
                            <td>
                                <div class="input-group input-group-sm">
                                    <input type="text" class="form-control" th:value="${p.message}">
                                </div>
                            </td>
                            <td style="width: 180px">
                                <button style="width: 150px;" onclick="sendOther(this)" class="btn btn-primary btn-sm" size="mini" type="button" th:text="${p.button}"></button>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                </div>
            </div>
        </div>

        <textarea wrap="off" id="message" class="form-control" style="height: 400px;margin-bottom: 20px;font-size: 13px" disabled></textarea>
    </div>
</body>

<script type="text/javascript">
    let websocket = null;

    let token = $('#token').val();
    let sendTopic = $('#sendTopic').val();
    let receiveTopic = $('#receiveTopic').val();
    let qos = $('#qos').val();

    let batchText = $('#batchText');
    let hideText = $('#hideText');
    hideText.text(batchText.val().split('\n')[0]);

    function base64encode(text) {
        //确保/不会被转义
        return btoa(text).replace(/\//g, "_");
    }

    //base64
    let sendTopic_base64 = base64encode(sendTopic);
    let receiveTopic_base64 = base64encode(receiveTopic);

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket( getNmqsWebsocket() + `/websocket/${token}/${sendTopic_base64}/${receiveTopic_base64}/${qos}`);

        console.log(getNmqsWebsocket() + `/websocket/${token}/${sendTopic_base64}/${receiveTopic_base64}/${qos}`)
    } else {
        alert('您的浏览器不支持WebSocket协议，建议您更换 Chrome 浏览器')
    }

    //如果连接成功
    if (websocket != null) {
        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            let prefix = "[System]["+ getTime() +"] ";
            setMessageInnerHTML(prefix + "开始建立连接");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            let prefix = "[Receive]["+ getTime() +"] ";
            setMessageInnerHTML(prefix + event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            let prefix = "[System]["+ getTime() +"] ";
            setMessageInnerHTML(prefix + "连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();

        }
    }

    function reConnect() {
        if ($('#sendTopic').val() === "" || $('#sendTopic').val() === null || $('#sendTopic').val() === undefined){
            alert("发送订阅不能为空！")
            return
        }

        if ($('#receiveTopic').val() === "" || $('#receiveTopic').val() === null || $('#receiveTopic').val() === undefined){
            alert("接收订阅不能为空！")
            return
        }

        if ($('#qos').val() === "" || $('#qos').val() === null || $('#qos').val() === undefined || $('#qos').val()>2 || $('#qos').val() <0){
            alert("QoS不正确")
            return;
        }

        closeWebSocket();

        setTimeout(function () {
            let sendTopic = $('#sendTopic').val();
            let receiveTopic = $('#receiveTopic').val();
            let qos = $('#qos').val();

            //base64
            let sendTopic_base64 = base64encode(sendTopic);
            let receiveTopic_base64 = base64encode(receiveTopic);

            websocket = new WebSocket( getNmqsWebsocket() + `/websocket/${token}/${sendTopic_base64}/${receiveTopic_base64}/${qos}`);

            console.log(getNmqsWebsocket() + `/websocket/${token}/${sendTopic_base64}/${receiveTopic_base64}/${qos}`)

            //如果连接成功
            if (websocket != null) {
                //连接发生错误的回调方法
                websocket.onerror = function () {
                    setMessageInnerHTML("error");
                };

                //连接成功建立的回调方法
                websocket.onopen = function (event) {
                    let prefix = "[System][" + getTime() + "] ";
                    setMessageInnerHTML(prefix + "开始建立连接");
                }

                //接收到消息的回调方法
                websocket.onmessage = function (event) {
                    let prefix = "[Receive][" + getTime() + "] ";
                    setMessageInnerHTML(prefix + event.data);
                }

                //连接关闭的回调方法
                websocket.onclose = function () {
                    let prefix = "[System][" + getTime() + "] ";
                    setMessageInnerHTML(prefix + "连接关闭");
                }

                //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = function () {
                    websocket.close();
                }
            }
        }, 1000)
    }

    function showHide() {
        let batchText = $('#batchText');
        let hideText = $('#hideText');
        let button = $('#showHide');
        if (batchText.css('display') === 'none') {
            batchText.css('display', 'block');
            hideText.css('display', 'none');
            button.text('▽');
        } else {
            batchText.css('display', 'none');

            hideText.css('display', 'block');

            button.text('▷');

            //只显示textarea的第一行
            hideText.text(batchText.val().split('\n')[0]);
        }
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        //$('#message').val(innerHTML + '\n' + $('#message').val());
        //只显示最上的1000行
        let message = $('#message').val();
        let messageArray = message.split('\n');
        if (messageArray.length > 500) {
            messageArray.pop();
        }
        messageArray.unshift(innerHTML);
        $('#message').val(messageArray.join('\n'));

    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        let message = document.getElementById('text').value;
        websocket.send(message);
        //如果发送成功
        if (websocket.readyState === 1) {
            let prefix = "[Send]["+ getTime() +"] ";
            setMessageInnerHTML(prefix + message);
        }
    }

    function sendOther(this1) {
        //获取按钮上面的input的值
        let message = $(this1).parent().parent().find('input').val();
        websocket.send(message);
        //如果发送成功
        if (websocket.readyState === 1) {
            let prefix = "[Send]["+ getTime() +"] ";
            setMessageInnerHTML(prefix + message);
        }
    }

    function getTime() {
        let date = new Date();
        let hours = String(date.getHours()).padStart(2, "0");
        let min = String(date.getMinutes()).padStart(2, "0");
        let sec = String(date.getSeconds()).padStart(2, "0");

        return `${hours}:${min}:${sec}`;
    }

    function batchSend() {
        let message = $('#batchText').val();
        let delay = $('#batchInterval').val();
        let messageArray = message.split('\n');
        let i = 0;
        let interval = setInterval(function () {
            if (i < messageArray.length) {
                websocket.send(messageArray[i]);
                let prefix = "[Send]["+ getTime() +"] ";
                setMessageInnerHTML(prefix + messageArray[i]);
                i++;
            } else {
                clearInterval(interval);
            }
        }, delay);
    }
</script>

<style>

    .form-group {
        flex: 1 0 33.33%;
        padding: 5px;
        margin-bottom: 10px;
    }

    @media (max-width: 768px) {
        .form-group {
            flex-basis: 100%;
        }
    }

    table.table {
        border: none; /* 去掉表格边框 */
    }

    table.table td {
        border: none; /* 去掉单元格边框 */
        padding: 5px 5px;
    }
</style>
</html>
